from ext import *


from entity.sysinfo.UserModel import UserModel

class UserController(Resource):
    def get(self):
        items = UserModel.query.all()
        rows = translist(items)
        return ok(rows)
    def post(self):
        jsonDict = request.get_json()
        model = toDbModel(UserModel(), jsonDict)
        db.session.add(model)
        db.session.commit()
        return ok(1)
    def put(self):
        jsonDict = request.get_json()
        model = toDbModel(UserModel(), jsonDict)
        db.session.merge(model)
        db.session.commit()
        return ok(1)
    def delete(self):
        db.session.execute(UserModel.__table__.delete())
        db.session.commit()
        return ok(1)

class UserPaginationController(Resource):
    def get(self):
        # 分页查询
        page = request.args.get('page')
        per_page = request.args.get('per_page')
        pageInfo = UserModel.query.paginate(page=int(page), per_page=int(per_page))
        print(vars(pageInfo))
        # 转化
        rows = translist(pageInfo.items)
        res = {"total": pageInfo.total, "rows": rows}
        return ok(res)

class UserDeleteByIdController(Resource):
    def delete(self, item_id):
        um = UserModel.query.get(item_id)
        db.session.delete(um)
        db.session.commit()
        return ok(1)

class UserGetByIdController(Resource):
    def get(self, item_id):
        um = UserModel.query.get(item_id)
        res = None if um is None else um.to_json
        return ok(res)